4-快速连接 FAST_CONNECT

1
2
//ConnectionServer#init()
messageDispatcher.register(Command.FAST_CONNECT, () -> new FastConnectHandler(mPushServer));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public final class FastConnectHandler extends BaseMessageHandler<FastConnectMessage> {
private final ReusableSessionManager reusableSessionManager;

public FastConnectHandler(MPushServer mPushServer) {
this.reusableSessionManager = mPushServer.getReusableSessionManager();
}

@Override
public FastConnectMessage decode(Packet packet, Connection connection) {
return new FastConnectMessage(packet, connection);
}

@Override
public void handle(FastConnectMessage message) {
//从缓存中心查询session
Profiler.enter("time cost on [query session]");
ReusableSession session = reusableSessionManager.querySession(message.sessionId);
Profiler.release();
if (session == null) {
//1.没查到说明session已经失效了
ErrorMessage.from(message).setErrorCode(SESSION_EXPIRED).send();
Logs.CONN.warn("fast connect failure, session is expired, sessionId={}, deviceId={}, conn={}"
, message.sessionId, message.deviceId, message.getConnection().getChannel());
} else if (!session.context.deviceId.equals(message.deviceId)) {
//2.非法的设备, 当前设备不是上次生成session时的设备
ErrorMessage.from(message).setErrorCode(INVALID_DEVICE).send();
Logs.CONN.warn("fast connect failure, not the same device, deviceId={}, session={}, conn={}"
, message.deviceId, session.context, message.getConnection().getChannel());
} else {
//3.校验成功,重新计算心跳,完成快速重连
int heartbeat = ConfigTools.getHeartbeat(message.minHeartbeat, message.maxHeartbeat);
session.context.setHeartbeat(heartbeat);

Profiler.enter("time cost on [send FastConnectOkMessage]");
FastConnectOkMessage
.from(message)
.setHeartbeat(heartbeat)
.sendRaw(f -> {
if (f.isSuccess()) {
//4. 恢复缓存的会话信息(包含会话密钥等)
message.getConnection().setSessionContext(session.context);
Logs.CONN.info("fast connect success, session={}, conn={}", session.context, message.getConnection().getChannel());
} else {
Logs.CONN.info("fast connect failure, session={}, conn={}", session.context, message.getConnection().getChannel());
}
});

Profiler.release();
}
}
}



接入服务文章目录:

------ 本文结束 感谢您的阅读 ------